<template>
    <div class="breadcrumb-box">
        <div class="container-fluid">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbStore.breadcrumbs" :key="index">
                    <router-link v-if="breadcrumb.to && index !== breadcrumbStore.breadcrumbs.length - 1" :to="link(breadcrumb)">{{
                        breadcrumb.title ? breadcrumb.title : $t(breadcrumb.titleKey || '')
                    }}</router-link>
                    <span v-else>{{ breadcrumb.title ? breadcrumb.title : $t(breadcrumb.titleKey || '') }}</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useBreadcrumbStore } from '@/stores/breadcrumb'
import type { BreadcrumbItem } from '@/types/router'
import { useRoute } from 'vue-router'

const breadcrumbStore = useBreadcrumbStore()
const route = useRoute()
const link = (breadcrumb: BreadcrumbItem) => {
    // console.log(breadcrumb)
    if (!breadcrumb.to) return ''
    if (breadcrumb.dynamic) {
        return extractParamNames(breadcrumb.to)
    } else {
        return breadcrumb.to
    }
}

function extractParamNames(pattern: string): string {
    const paramNames: string[] = []
    pattern.split('/').forEach(segment => {
        if (segment.startsWith(':')) {
            paramNames.push(route.params[segment.slice(1)] as string)
        } else {
            paramNames.push(segment)
        }
    })

    return paramNames.join('/')
}
</script>

<style lang="less" scoped>
.breadcrumb-box {
    background-color: #f4f4f4;

    .container-fluid {
        display: flex;
        align-items: center;
        height: 42px;
    }

    :deep(.el-breadcrumb) {
        .el-breadcrumb__item {
            .el-breadcrumb__inner {
                color: #4c4c4c;
                font-weight: normal;

                &.is-link:hover {
                    color: #f06423;
                }
            }
        }
    }
}

.page-box {
    padding: 45px 0;
}
</style>
